const qiniu = require('qiniu');

const QINIU_ZONE_HUADONG = 'z0';
const QINIU_ZONE_HUABEI = 'z1';
const QINIU_ZONE_HUANAN = 'z2';
const QINIU_ZONE_BEIMEI = 'na0';

// const QINIU_ZONE_UPLOAD = {
//   [QINIU_ZONE_HUADONG]: {
//     client: 'http://up.qiniup.com',
//     server: 'http://upload.qiniup.com'
//   },
//   [QINIU_ZONE_HUABEI]: {
//     client: 'http://up-z1.qiniup.com',
//     server: 'http://upload-z1.qiniup.com'
//   },
//   [QINIU_ZONE_HUANAN]: {
//     client: 'http://up-z2.qiniup.com',
//     server: 'http://upload-z2.qiniup.com'
//   },
//   [QINIU_ZONE_BEIMEI]: {
//     client: 'http://up-na0.qiniup.com',
//     server: 'http://upload-na0.qiniup.com'
//   }
// };

// 服务器上传zone对象
const QINIU_ZONE_OBJECT = {
  [QINIU_ZONE_HUADONG]: qiniu.zone.Zone_z0,
  [QINIU_ZONE_HUABEI]: qiniu.zone.Zone_z1,
  [QINIU_ZONE_HUANAN]: qiniu.zone.Zone_z2,
  [QINIU_ZONE_BEIMEI]: qiniu.zone.Zone_na0
};

function uptoken (accessKey, secretKey, bucket) {
  const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

  const options = {
    scope: bucket,
    expires: 1800,
    returnBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","w":"$(imageInfo.width)","h":"$(imageInfo.height)", "exifTime":$(exif.DateTimeOriginal.val)}',
    mimeLimit: 'image/jpeg;image/png'
  };
  const putPolicy = new qiniu.rs.PutPolicy(options);
  return putPolicy.uploadToken(mac);
}

/**
 * 上传文件到七牛
 *
 * @export
 * @param {path or buffer} localFile 文件地址或者文件buffer
 * @param {string} bucket
 * @returns
 */
module.exports = async function uploadFile (localFile, accessKey, secretKey, bucket, zone) {
  const uploadToken = uptoken(accessKey, secretKey, bucket);
  const config = new qiniu.conf.Config();
  // 空间对应的机房
  config.zone = QINIU_ZONE_OBJECT[zone];

  var formUploader = new qiniu.form_up.FormUploader(config);
  var putExtra = new qiniu.form_up.PutExtra();
  const result = await new Promise((resolve, reject) => {
    formUploader.putStream(uploadToken, '', localFile, putExtra, function (respErr,
      respBody, respInfo) {
      if (respErr) {
        reject(respErr);
      } else {
        resolve({
          header: respInfo,
          body: respBody
        });
      }
    });
  });
  if (result.header.statusCode === 200) {
    return result;
  } else {
    return null;
  }

  // var extra = new qiniu.io.PutExtra()
  // return new Promise((resolve, reject) => {
  //   qiniu.io.putWithoutKey(uptoken(bucket), localFile, extra, function (err, ret) {
  //     if (!err) {
  //             // 上传成功， 处理返回值
  //       resolve({ hash: ret.hash, key: ret.key })
  //     } else {
  //             // 上传失败， 处理返回代码
  //       reject(err)
  //     }
  //   })
  // })
};
